package servlet.news;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import bean.News;
import dao.NewsDAO;
import util.MultipartFormUtil;

/**
 * Servlet implementation class UpdateNews
 */
@WebServlet("/UpdateNews")
public class UpdateNews extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UpdateNews() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 * 
	 *      根据表单信息更新新闻，可部分更新
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");

		String title = null;
		String text = null;
		InputStream img = null;
		String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		int id = Integer.valueOf(request.getParameter("id"));
		List<FileItem> formItems = MultipartFormUtil.getFormItems(request, response);
		if (formItems != null) {
			for (FileItem e : formItems) {
				if (e.isFormField()) {
					String fieldName = e.getFieldName();
					if ("title".equals(fieldName)) {
						title = new String(e.getString().getBytes("ISO8859_1"), "utf-8");
					} else if ("text".equals(fieldName)) {
						text = new String(e.getString().getBytes("ISO8859_1"), "utf-8");
					}
				} else {
					img = e.getInputStream();
				}
			}
		}
		News news = new News();
		news.setId(id);
		news.setTitle(title);
		news.setText(text);
		news.setTime(time);
		news.setImg(img);
		NewsDAO newsDAO = new NewsDAO();
		boolean success = newsDAO.updateNews(news);
		request.setAttribute("success", success);
		int currentPage = (int) (request.getSession().getAttribute("currentPage"));
		response.sendRedirect("./jsp/manage/manageNews.jsp?currentPage=" + currentPage);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
